package com.combetter.changxing.http.base;



import com.combetter.changxing.BuildConfig;
import com.combetter.changxing.constanst.Urls;
import com.combetter.changxing.http.APIService;
import com.combetter.changxing.http.cookies.AddCookiesInterceptor;
import com.combetter.changxing.http.cookies.ReceivedCookiesInterceptor;
import com.combetter.changxing.utils.MyUtils;


import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author: qintao
 * E-mail: 954280376@qq.com
 * Date: 2018/3/22 22:54
 * Description: Api
 */

public class Api {

    private static APIService apiService;

    public static APIService getApiService() {
        if (apiService == null) {
            //创建okhttpClient
            OkHttpClient.Builder okhttpBuilder = new OkHttpClient.Builder();
            //设置超时
            okhttpBuilder.connectTimeout(20, TimeUnit.SECONDS);
            okhttpBuilder.readTimeout(20, TimeUnit.SECONDS);
            okhttpBuilder.writeTimeout(20, TimeUnit.SECONDS);

          //缓存
            File cacheDir = new File(MyUtils.getApp().getCacheDir(), "responses");
            int cacheSize = 10 * 1024 * 1024; //10MB
            okhttpBuilder.cache(new Cache(cacheDir, cacheSize));

            //Cookies添加拦截器
            okhttpBuilder.addInterceptor(new AddCookiesInterceptor());
            //Cookies接收拦截器
            okhttpBuilder.addInterceptor(new ReceivedCookiesInterceptor());

            //添加LOG日志拦截
            if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                okhttpBuilder.addInterceptor(interceptor);
            }

            //创建APIService
            apiService = new Retrofit.Builder()
                    .client(okhttpBuilder.build())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .baseUrl(Urls.BASE_IP)
                    .build().create(APIService.class);
        }
        return apiService;
    }
}
